package redis.client.nedis.util;

import io.netty.channel.Channel;
import redis.client.nedis.HostAndPort;
import redis.client.nedis.request.RedisRequest;
import redis.client.nedis.request.RedisRequestQueue;
import redis.client.nedis.request.RequestPool;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gaodong
 */
public class RedisRequestUtil {

    private static Map<HostAndPort, Long> idMap = new HashMap<>();

    /**
     * 发送Request请求
     */
    public synchronized static Channel sendRequests(Channel channel, RedisRequest... requests) {

        long s = System.nanoTime();
        try {
            for (RedisRequest rq : requests) {

                //rq.getSemaphore().acquire();

                /*HostAndPort hp = rq.getHostAndPort();
                Long id = idMap.get(hp);
                if (id == null) {
                    id = UnsafeIdUtil.Init;
                }

                rq.setId(id);
                RequestPool.putRequest(rq);

                idMap.put(hp, UnsafeIdUtil.getNextId(id));*/

                RedisRequestQueue.getInstance().off(rq.getHostAndPort(), rq);

                channel.write(rq.getCommand());
            }
        } catch (Exception ex) {
        }
        Channel c = channel.flush();

        long e = System.nanoTime();
        System.out.println("write=" + (e - s) / 1e6 + "ms");

        return c;
    }
}
